import { defineStore } from "pinia";
import { computed, ref } from "vue";

export const useCart = defineStore("cart", () => {
  let state = JSON.parse(localStorage.getItem("cartStoreState") as string);

  //定义大数据 相应于是 state
  let name = ref(state?.value || "鲁花压榨葵花仁油5L");
  let count = ref(state?.price || 19.8);
  let price = ref(state?.count || 1);

  //     //减少数量  定义的方法相当于  Action
  function subCount() {
    if (count.value == 1) {
      return;
    }
    count.value--;
  }

  function plusCount() {
    if (count.value >= 100) {
      alert("不能再多了");
      return;
    }
    count.value++;
  }

  //计算属性 相当于  getters

  let amount = computed(() => {
    return parseFloat((price.value * count.value).toFixed(2));
  });

  //暴露在 store上的数据、属性、函数 使用return
  return {
    name,
    price,
    count,
    amount,
    subCount,
    plusCount,
  };
});
